package logic

import (
	"context"
	"errors"
	"fresh-box-manage/models/mysql"
	"gorm.io/gorm"

	"fresh-box-manage/freshrpc/freshrpc"
	"fresh-box-manage/freshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshUpdateLogic {
	return &FreshUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改
func (l *FreshUpdateLogic) FreshUpdate(in *freshrpc.FreshUpdateRequest) (*freshrpc.FreshUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var fresh mysql.Fresh

	if err := fresh.FreshFindById(mysql.DB, in.FreshId); err != nil {
		return nil, errors.New("该商品不存在,不允许修改")
	}

	fresh = mysql.Fresh{
		Model: gorm.Model{ID: uint(in.FreshId)},
		Name:  in.Name,
		Price: float64(in.Price),
		Num:   int(in.Num),
	}

	if err := fresh.FreshUpdate(mysql.DB); err != nil {
		return nil, err
	}

	return &freshrpc.FreshUpdateResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
